import pandas as pd
from snownlp import SnowNLP
import time
from tqdm import tqdm


class SentimentLexicon:
    def __init__(self, pos_dict='positive_words.txt', neg_dict='negative_words.txt'):

        with open(pos_dict, 'r', encoding='utf-8') as f:
            self.pos_words = set([line.strip() for line in f if line.strip()])

        with open(neg_dict, 'r', encoding='utf-8') as f:
            self.neg_words = set([line.strip() for line in f if line.strip()])

        print(f"情感词典加载完成 - 正向词: {len(self.pos_words)}个, 负向词: {len(self.neg_words)}个")

    def analyze(self, text):
        pos_count = 0
        neg_count = 0

        words = jieba.lcut(text)
        for word in words:
            if word in self.pos_words:
                pos_count += 1
            elif word in self.neg_words:
                neg_count += 1

        total = pos_count + neg_count
        if total == 0:
            return 0.5  # 中性

        score = pos_count / total
        return score


def sentiment_analysis(df):
    results = []

    print("\n[方法1] 正在使用SnowNLP进行情感分析...")
    snownlp_scores = []
    for text in tqdm(df['评论内容'], desc="SnowNLP处理进度"):
        try:
            score = SnowNLP(text).sentiments
            snownlp_scores.append(score)
        except:
            snownlp_scores.append(0.5)  # 分析失败设为中性

    # 方法2: 情感词典（需准备词典文件）
    print("\n[方法2] 正在使用情感词典进行分析...")
    try:
        lexicon = SentimentLexicon()
        lexicon_scores = []
        for text in tqdm(df['评论内容'], desc="情感词典处理进度"):
            score = lexicon.analyze(text)
            lexicon_scores.append(score)
    except Exception as e:
        print(f"情感词典加载失败: {str(e)}")
        lexicon_scores = [0.5] * len(df)  # 全部设为中性

    df['SnowNLP情感分'] = snownlp_scores
    df['词典情感分'] = lexicon_scores

    df['最终情感分析'] = df.apply(lambda x:
                                  '正面' if (x['SnowNLP情感分'] + x['词典情感分']) / 2 > 0.6 else
                                  ('负面' if (x['SnowNLP情感分'] + x['词典情感分']) / 2 < 0.4 else '中性'),
                                  axis=1)

    return df


if __name__ == '__main__':

    try:
        df = pd.read_csv('data_processed.csv', encoding='utf-8-sig')
        print(f"成功加载数据，共 {len(df)} 条记录")
    except Exception as e:
        print(f"加载数据失败: {str(e)}")
        exit()

    start_time = time.time()
    df = sentiment_analysis(df)
    print(f"\n情感分析完成，耗时: {time.time() - start_time:.2f}秒")

    output_file = 'data_with_sentiment.csv'
    df.to_csv(output_file, index=False, encoding='utf-8-sig')
    print(f"结果已保存到: {output_file}")

    print("\n情感分布统计:")
    print(df['最终情感分析'].value_counts())

    print("\n情感分析样例:")
    print(df[['评论内容', 'SnowNLP情感分', '词典情感分', '最终情感分析']].sample(5))